<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>IoT Gateway Management</title>
    <!-- CSS Styles -->
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 0;
            margin: 0;
            background-color: #f4f4f4;
        }

        .sidebar {
            width: 250px;
            height: 100vh;
            background: #2c3e50;
            color: white;
            position: fixed;
            padding-top: 20px;
        }

        .sidebar h2 {
            text-align: center;
            color: #ecf0f1;
        }

        .sidebar ul {
            list-style: none;
            padding: 0;
        }

        .sidebar ul li {
            padding: 15px;
            cursor: pointer;
            text-align: center;
            transition: 0.3s;
        }

        .sidebar ul li:hover {
            background: #34495e;
        }

        .main-content {
            margin-left: 250px;
            padding: 20px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #ffffff;
            padding: 10px 20px;
            border-bottom: 2px solid #ddd;
        }

        .user-info {
            display: flex;
            align-items: center;
            cursor: pointer;
            position: relative;
        }

        .user-info img {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            margin-right: 10px;
        }

        .dropdown {
            display: none;
            position: absolute;
            right: 0;
            top: 40px;
            background: white;
            border: 1px solid #ccc;
            box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
        }

        .dropdown a {
            display: block;
            padding: 10px;
            text-decoration: none;
            color: black;
        }

        .dropdown a:hover {
            background: #f0f0f0;
        }

        .tab {
            display: none;
            padding: 20px;
            border-radius: 8px;
            background: #ffffff;
            margin-top: 20px;
        }

        .active {
            display: block;
        }

        button {
            padding: 10px 15px;
            cursor: pointer;
            border: none;
            background: #3498db;
            color: white;
            border-radius: 5px;
            transition: 0.3s;
        }

        button:hover {
            background: #2980b9;
        }

        input,
        select {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        label {
            font-weight: bold;
            display: block;
            margin-top: 10px;
        }

        .control-panel {
            padding: 20px;
            background: #f5f5f5;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .button-group {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 30px;
        }

        .control-btn {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 15px;
            border: none;
            border-radius: 8px;
            background: #ffffff;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .control-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            background: #f0f0f0;
        }

        .control-btn:active {
            transform: translateY(0);
            background: #e0e0e0;
        }

        .btn-icon {
            font-size: 24px;
            margin-bottom: 8px;
        }

        .btn-text {
            font-size: 14px;
            color: #333;
        }

        .data-display {
            margin-top: 20px;
            padding: 15px;
            background: #ffffff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .data-container {
            min-height: 100px;
            max-height: 200px;
            overflow-y: auto;
            padding: 10px;
            background: #f9f9f9;
            border-radius: 4px;
            border: 1px solid #eee;
        }

        .status-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 5px;
        }

        .status-connected {
            background-color: #2ecc71;
        }

        .status-disconnected {
            background-color: #e74c3c;
        }
    </style>
</head>

<body>
    <div class="sidebar">
        <h2>IoT Gateway</h2>
        <ul>
            <li onclick="showTab('status')">Gateway Overview</li>
            <li onclick="showTab('control')">Device Control</li>
            <li onclick="showTab('config')">Gateway Configuration</li>
            <li onclick="showTab('server')">Server Configuration</li>
            <li onclick="showTab('language')">Language</li>
        </ul>
    </div>

    <div class="main-content">
        <div class="header">
            <h2>Dashboard</h2>
            <div class="user-info" onclick="toggleDropdown()">
                <img src=""
                    alt="User" />
                <span>Admin</span>
                <div class="dropdown" id="userDropdown">
                    <a href="#" onclick="logout()">Logout</a>
                </div>
            </div>
        </div>

        <div id="status" class="tab active">
            <h3>Gateway Overview</h3>
            <p><strong>User:</strong> <span id="user">admin</span></p>
            <p>
                <strong>WebSocket Status:</strong>
                <span class="status-indicator" id="ws-status-indicator"></span>
                <span id="ws-status">Disconnected</span>
            </p>
            <p>
                <strong>WiFi Connection:</strong>
                <span class="status-indicator" id="wifi-status-indicator"></span>
                <span id="wifiStatus">Disconnected</span> (IP:
                <span id="wifiIP">N/A</span>)
            </p>
            <p>
                <strong>Ethernet Connection:</strong>
                <span class="status-indicator" id="eth-status-indicator"></span>
                <span id="ethStatus">Disconnected</span> (IP:
                <span id="ethIP">N/A</span>)
            </p>
            <p>
                <strong>Memory Usage:</strong>
                <span id="memoryUsage">N/A</span>
            </p>
            <p>
                <strong>TCP Server:</strong>
                <span id="tcpServer">N/A</span>
            </p>
            <p>
                <strong>Counter:</strong>
                <span id="systemCounter">N/A</span>
            </p>
        </div>

        <div id="control" class="tab">
            <div class="control-panel">
                <h3>Device Control</h3>
                <div class="button-group">
                    <button class="control-btn" onclick="sendCommand('cmd1')">
                        <span class="btn-icon">📡</span>
                        <span class="btn-text">Command 1</span>
                    </button>
                    <button class="control-btn" onclick="sendCommand('cmd2')">
                        <span class="btn-icon">🔄</span>
                        <span class="btn-text">Command 2</span>
                    </button>
                    <button class="control-btn" onclick="sendCommand('cmd3')">
                        <span class="btn-icon">⚡</span>
                        <span class="btn-text">Command 3</span>
                    </button>
                    <button class="control-btn" onclick="sendCommand('cmd4')">
                        <span class="btn-icon">🔌</span>
                        <span class="btn-text">Command 4</span>
                    </button>
                    <button class="control-btn" onclick="sendCommand('cmd5')">
                        <span class="btn-icon">⚙️</span>
                        <span class="btn-text">Command 5</span>
                    </button>
                </div>
                <div class="data-display">
                    <h4>Command Response</h4>
                    <div id="dataContainer" class="data-container">
                        <p>No response yet...</p>
                    </div>
                </div>

                <div class="data-display">
                    <h4>TCP Server Data Response</h4>
                    <div id="tcpDataContainer" class="data-container">
                        <p>No response yet...</p>
                    </div>
                    <input type="text" id="messageInput" placeholder="Please input" style="width:300px;">
                    <button id="sendBtn" onclick="sendTcpData()">send</button>
                </div>
            </div>
        </div>

        <div id="config" class="tab">
            <h3>Gateway Configuration</h3>
            <label>WiFi SSID: <input type="text" id="ssid" /></label>
            <label>Password: <input type="password" id="password" /></label>
            <label>Ethernet DHCP:
                <input type="checkbox" id="dhcp" checked onchange="toggleStaticIP()" />
            </label>
            <div id="staticIPConfig" style="display: none">
                <label>Static IP: <input type="text" id="staticIP" /></label>
                <label>Subnet Mask: <input type="text" id="subnet" /></label>
                <label>Gateway: <input type="text" id="gateway" /></label>
            </div>
            <button onclick="saveConfig()">Save Configuration</button>
        </div>

        <div id="server" class="tab">
            <h3>Server Configuration</h3>
            <label>TCP Mode:
                <select id="tcpMode">
                    <option>TCP Client</option>
                    <option>TCP Server</option>
                </select>
            </label>
            <label>UDP Port: <input type="text" id="udpPort" /></label>
            <label>MQTT Server: <input type="text" id="mqttServer" /></label>
            <label>Username: <input type="text" id="mqttUser" /></label>
            <label>Password: <input type="password" id="mqttPassword" /></label>
            <button onclick="saveServerConfig()">
                Save Server Configuration
            </button>
        </div>

        <div id="language" class="tab">
            <h3>Language</h3>
            <select id="languageSelect" onchange="setLanguage()">
                <option value="en">English</option>
                <option value="zh">中文</option>
                <option value="pt">Português</option>
            </select>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // WebSocket Management
        let ws;
        const reconnectDelay = 5000;

        const WS_CONFIG = {
            host: "esp-home.local", // ESP32的IP地址
            port: 80, // WebSocket端口
            path: "/ws", // WebSocket路径
        };

        function initWebSocket() {
            const protocol =
                window.location.protocol === "https:" ? "wss:" : "ws:";
            const wsUrl = `ws://${WS_CONFIG.host}:${WS_CONFIG.port}${WS_CONFIG.path}`;

            ws = new WebSocket(wsUrl);

            ws.onopen = () => {
                console.log("WebSocket Connected");
                updateWSStatus(true);
                requestInitialStatus();
            };

            ws.onclose = () => {
                console.log("WebSocket Disconnected");
                updateWSStatus(false);
                setTimeout(initWebSocket, reconnectDelay);
            };

            ws.onerror = (error) => {
                console.error("WebSocket Error:", error);
                updateWSStatus(false);
            };

            ws.onmessage = (event) => {
                try {
                    const data = JSON.parse(event.data);
                    handleWebSocketMessage(data);
                } catch (error) {
                    console.error("Error parsing message:", error);
                }
            };
        }

        function updateWSStatus(connected) {
            const indicator = document.getElementById(
                "ws-status-indicator",
            );
            const status = document.getElementById("ws-status");

            if (connected) {
                indicator.className = "status-indicator status-connected";
                status.textContent = "Connected";
            } else {
                indicator.className =
                    "status-indicator status-disconnected";
                status.textContent = "Disconnected";
            }
        }

        function handleWebSocketMessage(data) {
            switch (data.type) {
                case "status":
                    updateStatusInfo(data);
                    break;
                case "control_response":
                    updateDataDisplay(data.message);
                    break;
                case "config":
                    updateConfigInfo(data);
                    break;

                case "tcp_server_data":
                    updateTcpDataDisplay(data.message)
                    break;

                default:
                    console.log("Unknown message type:", data.type);
            }
        }

        function updateStatusInfo(data) {
            document.getElementById("user").textContent =
                data.user || "admin";

            // Update WiFi status
            const wifiIndicator = document.getElementById(
                "wifi-status-indicator",
            );
            document.getElementById("wifiStatus").textContent =
                data.wifi_status || "Disconnected";
            document.getElementById("wifiIP").textContent =
                data.wifi_ip || "N/A";
            wifiIndicator.className = `status-indicator status-${data.wifi_status === "Connected" ? "connected" : "disconnected"}`;

            // Update Ethernet status
            const ethIndicator = document.getElementById(
                "eth-status-indicator",
            );
            document.getElementById("ethStatus").textContent =
                data.eth_status || "Disconnected";
            document.getElementById("ethIP").textContent =
                data.eth_ip || "N/A";
            ethIndicator.className = `status-indicator status-${data.eth_status === "Connected" ? "connected" : "disconnected"}`;

            document.getElementById("memoryUsage").textContent =
                data.memory_usage || "N/A";

            document.getElementById("tcpServer").textContent =
                data.tcp_server || "N/A"

            document.getElementById("systemCounter").textContent =
                data.system_counter || "0";
        }

        function sendWebSocketMessage(message) {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify(message));
            } else {
                console.warn("WebSocket is not connected");
                updateDataDisplay("System: WebSocket not connected");
            }
        }

        function requestInitialStatus() {
            sendWebSocketMessage({
                type: "request",
                action: "get_status",
            });
        }

        // UI Functions
        function showTab(tabId) {
            document
                .querySelectorAll(".tab")
                .forEach((tab) => tab.classList.remove("active"));
            const tabElement = document.getElementById(tabId);
            if (tabElement) {
                tabElement.classList.add("active");
            }
        }

        function toggleDropdown() {
            const dropdown = document.getElementById("userDropdown");
            dropdown.style.display =
                dropdown.style.display === "block" ? "none" : "block";
        }

        function toggleStaticIP() {
            const dhcpChecked = document.getElementById("dhcp").checked;
            document.getElementById("staticIPConfig").style.display =
                dhcpChecked ? "none" : "block";
        }

        // Command Functions
        function sendCommand(cmd) {
            const btn = event.currentTarget;
            btn.style.transform = "scale(0.95)";
            setTimeout(() => (btn.style.transform = "scale(1)"), 200);

            sendWebSocketMessage({
                type: "control",
                command: cmd,
            });

            updateDataDisplay(`Sent command: ${cmd}`);
        }

        function sendTcpData() {
            var msg = document.getElementById('messageInput').value;
            if (msg.trim() === '') {
                alert('请输入消息');
                return;
            }

            sendWebSocketMessage({
                type: "tcp_server_control",
                command: msg,
            });
        }

        function updateDataDisplay(data) {
            const container = document.getElementById("dataContainer");
            const newData = document.createElement("p");
            newData.textContent = `${new Date().toLocaleTimeString()}: ${data}`;
            container.insertBefore(newData, container.firstChild);

            if (container.children.length > 10) {
                container.removeChild(container.lastChild);
            }
        }

        function updateTcpDataDisplay(data) {
            const container = document.getElementById("tcpDataContainer");
            const newData = document.createElement("p");
            newData.textContent = `${new Date().toLocaleTimeString()}: ${data}`;
            container.insertBefore(newData, container.firstChild);

            if (container.children.length > 10) {
                container.removeChild(container.lastChild);
            }
        }

        // Configuration Functions
        function saveConfig() {
            const config = {
                type: "config",
                action: "save",
                data: {
                    wifi: {
                        ssid: document.getElementById("ssid").value,
                        password: document.getElementById("password").value,
                    },
                    ethernet: {
                        dhcp: document.getElementById("dhcp").checked,
                        static_ip:
                            document.getElementById("staticIP").value,
                        subnet: document.getElementById("subnet").value,
                        gateway: document.getElementById("gateway").value,
                    },
                },
            };

            sendWebSocketMessage(config);
        }

        function saveServerConfig() {
            const config = {
                type: "server_config",
                action: "save",
                data: {
                    tcp_mode: document.getElementById("tcpMode").value,
                    udp_port: document.getElementById("udpPort").value,
                    mqtt: {
                        server: document.getElementById("mqttServer").value,
                        user: document.getElementById("mqttUser").value,
                        password:
                            document.getElementById("mqttPassword").value,
                    },
                },
            };

            sendWebSocketMessage(config);
        }

        function setLanguage() {
            const lang = document.getElementById("languageSelect").value;
            sendWebSocketMessage({
                type: "config",
                action: "set_language",
                data: { language: lang },
            });
        }

        function logout() {
            // Add logout logic here
            console.log("Logout clicked");
        }

        // Initialize WebSocket when page loads
        window.addEventListener("load", () => {
            initWebSocket();

            // Close dropdown when clicking outside
            document.addEventListener("click", (event) => {
                if (!event.target.closest(".user-info")) {
                    document.getElementById("userDropdown").style.display =
                        "none";
                }
            });
        });

        // Cleanup WebSocket when page unloads
        window.addEventListener("beforeunload", () => {
            if (ws) {
                ws.close();
            }
        });
    </script>
</body>

</html>